<?php
namespace ManagerX\Controller;
use Think\Controller;
class ProjectController extends Controller {
    public function index(){
    }

    public function project_list(){
        if(session('?user')){
            $this->display('project_list');
        }else{
            $this->error('尚未登陆。', 'User/login', 3);
        }
    }

    public function project_add(){
        if(session('?user')){
            $template = M('template')->field('id, name, desc')->select();
            $payload = M('payload')->field('id, name, desc')->select();

            $this->assign('payloads', $payload);
            $this->assign('templates', $template);
            $this->display('project_add');
        }else{
            $this->error('尚未登陆。', 'User/login', 3);
        }
    }

    public function project_data(){
        if(session('?user')){
            // 将通知设置为已读
            M('notice')->where(array('user_id'=>session('user.id'), 'projecct_id'=>intval(I('get.id')), 'readed'=>0))->save(array('readed'=>1));
            $getscript = M('config')->where(array('name'=>'getscript'))->find();

            $this->assign('project_id', intval(I('get.id')));
            $this->assign('getscript', $getscript['value']);
            $this->display('project_data');
        }else{
            $this->error('尚未登陆。', 'User/login', 3);
        }
    }

    public function project_data_download(){
        if(session('?user')){
            // 验证是否有查看权限
            $project = M('project')->where(array('id'=>I('get.project_id')))->find();
            if(session('user.role') == 2 && session('user.id') != $project['user_id']){
                $this->error('没有权限。', 'User/login', 3);
            }else{
                $result = M('project_data')->where(array('project'=>I('get.project_id')))->select();
                header('Content-Type: text/csv');
                header('Content-Disposition: attachment; filename="export_'.I('get.project_id').'.csv"');
                $output = fopen('php://output', 'w');
                if (!empty($result)) {
                    fputcsv($output, array_keys($result[0])); // 写入列名
                }
                foreach ($result as $row) {
                    fputcsv($output, $row);
                }
                fclose($output);
            }
        }else{
            $this->error('尚未登陆。', 'User/login', 3);
        }
    }
}